#include "StdAfx.h"
#include "Messenger.h"
#include "GameObject.h"

BEGIN_XML_CONFIG_LOADER(Messenger)
	XML_CONFIG_LOADER_LINK_INTEGER(_SleepDuration, "sleepduration")
END_XML_CONFIG_LOADER

Messenger::Messenger(void) : GameObject(ClassMessenger), XmlConfigLoader("config\\messenger.xml")
{
}

Messenger::~Messenger(void)
{
	_SignalList.clear();
	_MessageList.clear();
}

void Messenger::AddMessage(shared_ptr<Msg> message)
{
	if (message == NULL)
		return;

	_MessageList.push_back(message);
}

void Messenger::AddSignal(shared_ptr<Sgn> signal)
{
	if (signal == NULL)
		return;

	_SignalList.push_back(signal);
}

void Messenger::OnRun(void)
{
	while (IsStopping() == false)
	{
		while (_MessageList.size() > 0 || _SignalList.size() > 0)
		{
			if (_MessageList.size() > 0)
			{
				shared_ptr<Msg> msg = _MessageList.front();
				_MessageList.erase(_MessageList.begin());
				ASSERT(msg.get() != NULL);
				if (msg.get() != NULL)
				{
					msg->GetTo()->OnMessage(msg->GetFrom(), msg->GetParam1(), msg->GetParam2());
				}
			}
			if (_SignalList.size() > 0)
			{
				shared_ptr<Sgn> sgn = _SignalList.front();
				_SignalList.erase(_SignalList.begin());
				ASSERT(sgn.get() != NULL);
				if (sgn.get() != NULL)
				{
					for (GameObject::List::iterator it = sgn->GetTo()->begin();
						it != sgn->GetTo()->end(); it++)
					{
						GameObject * pgo = *it;
						pgo->OnSignal(sgn->GetFrom(), sgn->GetCode());
					}
				}
			}
		}
		Sleep(_SleepDuration);
		Signal(Sgn::MessengerBeat);
	}
}

HRESULT Messenger::OnInitSingleton(void)
{
	HRESULT hr;
	CHECKHR(ReadConfiguration());
	return S_OK;
}


